/**
 * Created by xmgong on 2017/10/26.
 * 店铺完善
 */

import React from  'react';
import {connect} from 'react-redux';
import {
    View, 
    Text, 
    ScrollView, 
    TextInput, 
    Image, 
    TouchableOpacity,
    Dimensions
} from 'react-native';
import styles from './styles';
import CheckBox from 'react-native-checkbox';
import themeconfig from '../../config/theme';
import {getQiniuToken} from '../../utils/commonHttp';
import {chooseImage, toast, chooseLocation, ChooseCity, editRichContent} from '../../utils/NativeUtil';
import config from '../../config/config';
import ActionSheet from 'react-native-actionsheet';
import {getShopInfoCallBack, saveShopInfo, submitShopInfo, authShops} from './actions';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import {naviBack} from '../../navigatorApp/actions';
import {getShopInfo} from '../main/actions';
import {navi} from '../../utils/NativeUtil';

const IMGTYPE = {
    ShopImage: 'shop',
    ShopLogo: 'shoplogo',
    ShopBrand: 'shopbrand'
};
const CANCEL_INDEX = 0;
const options = ['取消', '拍照', '相册'];


class ShopComplete extends React.Component {


    static navigationOptions = ({navigation, screenProps}) => {
        const {params = {}} = navigation.state;
        let header = (<CLNavigatorHeader navigation={navigation} title="完善店铺" 
                                         rightTitle="保存"
                                         rightAction={params.saveAction}
                      />);
        return {header}
    };

    constructor(props) {
        super(props);
        this.QiNiuToken = '';//七牛Token
        this.ImgType = '';//照片类型
        this.state = {
            shoplogo: '',
            shopImgUri: '',
            shopName: '',
            phone: '',
            address: '',
            point_jd: '',
            cityName: '',
            cityCode: '',
            point_wd: '',
            pointstate: '未选',
            // brand: '',
            isChecked: false,
            shopId: '',
            story: '',
            storyState: '未编辑',
            brandLicence: ''
        }
    }

    componentDidMount() {
        this.props.navigation.setParams({saveAction: this.saveAction});
        let self = this;
        if (this.props.token.length > 0) {
            this.props.getShopInfoCallBack(this.props.token, function (shopinfo) {
                self.setState({
                    shoplogo: shopinfo.logo,
                    shopImgUri: shopinfo.backgroundImg,
                    shopName: shopinfo.shopName,
                    phone: shopinfo.phone,
                    address: shopinfo.address,
                    point_jd: shopinfo.lng,
                    cityName: shopinfo.cityName,
                    cityCode: shopinfo.cityCode,
                    point_wd: shopinfo.lat,
                    pointstate: shopinfo.lng ? '已选' : '未选',
                    isChecked: false,
                    shopId: shopinfo.shopId,
                    story: shopinfo.story,
                    storyState: (shopinfo.story == '' || shopinfo.story == undefined) ? '未编辑' : '已编辑',
                    brandLicence: shopinfo.brandLicence
                })
            });
        }
    }

    handlePress = (i) => {
        let phototype = '';
        if (i == 1) {
            phototype = 'takephoto'
        } else if (i == 2) {
            phototype = 'choose'
        } else {
            return;
        }

        let params = {};
        if (this.ImgType == IMGTYPE.ShopLogo) {
            params = {
                type: phototype,
                size_w: 100,
                size_h: 100,
                token: this.QiNiuToken,
                filetag: 'shop'
            };
        } else if (this.ImgType == IMGTYPE.ShopImage) {
            params = {
                type: phototype,
                size_w: 500,
                size_h: 400,
                token: this.QiNiuToken,
                filetag: 'shop'
            };
        } else if (this.ImgType == IMGTYPE.ShopBrand) {
            params = {
                type: phototype,
                size_w: 400,
                size_h: 600,
                token: this.QiNiuToken,
                filetag: 'shop'
            };
        }

        let self = this;
        chooseImage(params, function (res) {
            let imgUrl = config.qiniuUrl + res.imgs;
            if (self.ImgType == IMGTYPE.ShopLogo) {
                self.setState({
                    shoplogo: imgUrl
                });
            } else if (self.ImgType == IMGTYPE.ShopImage) {
                self.setState({
                    shopImgUri: imgUrl
                });
            } else if (self.ImgType == IMGTYPE.ShopBrand) {
                let temp = self.state.brandLicence;
                if (temp == undefined || temp == '') {
                    temp = imgUrl
                } else {
                    temp = temp + ';' + imgUrl
                }
                self.setState({
                    brandLicence: temp
                });
            }
        });
    };


    chooseImg = (type) => {
        let self = this;
        getQiniuToken(function (res) {
            self.QiNiuToken = res.token;
            self.ImgType = type;
            self.ActionSheet.show();
        }, function (message) {
            toast(message);
        })
    };


    saveAction = () => {
        let self = this;

        if (self.state.shopName.length == 0) {
            toast("店铺名称不能为空哦!");
            return;
        }

        let shopJson = {
            shopName: self.state.shopName,
            cityCode: self.state.cityCode,
            cityName: self.state.cityName,
            address: self.state.address,
            lng: self.state.point_jd,
            lat: self.state.point_wd,
            logo: self.state.shoplogo,
            shopId: self.state.shopId,
            backgroundImg: self.state.shopImgUri,
            story: self.state.story,
            brandLicence: self.state.brandLicence
        };

        let params = {
            token: self.props.userToken,
            shopString: JSON.stringify(shopJson),
        };

        this.props.saveShopInfo(params, function () {
            toast("保存成功");
            self.props.getShopInfo();
            self.props.naviBack();
        });
    };


    submitAction = () => {

        if (this.state.shoplogo == '') {
            toast('请选择店铺logo');
            return;
        }

        if (this.state.shopName == '') {
            toast('请填写店铺名');
            return;
        }

        if (this.state.phone == '') {
            toast('请填写联系电话');
            return;
        }

        if (this.state.cityCode == '') {
            toast('请选择城市');
            return;
        }

        if (this.state.address == '') {
            toast('请填写店铺详细地址');
            return;
        }

        if (this.state.point_jd == '') {
            toast('请选择店铺位置');
            return;
        }

        if (this.state.shopImgUri == '') {
            toast('请选择门店照片');
            return;
        }

        if (this.state.storyState == '未编辑') {
            toast('请编辑店铺详情');
            return;
        }

        if (!this.state.isChecked) {
            toast('请先阅读合同');
            return;
        }

        let self = this;
        let shopJson = {
            shopName: self.state.shopName,
            phone: self.state.phone,
            cityCode: self.state.cityCode,
            cityName: self.state.cityName,
            address: self.state.address,
            lng: self.state.point_jd,
            lat: self.state.point_wd,
            logo: self.state.shoplogo,
            shopId: self.state.shopId,
            backgroundImg: self.state.shopImgUri,
            story: self.state.story,
            brandLicence: self.state.brandLicence
        };

        let params = {
            token: self.props.userToken,
            shopString: JSON.stringify(shopJson),
        };

        this.props.submitShopInfo(params, function (res) {
            toast("提交成功");
            self.props.getShopInfo();
            self.props.naviBack();
        })
    };

    changeIsRead = (checked) => {
        this.setState({isChecked: !checked})
    };

    changePlace = () => {
        let self = this;
        chooseLocation({lat: this.state.point_wd, lon: this.state.point_jd}, function (res) {
            let lat = res.lat;
            let lon = res.lon;
            self.setState({pointstate: '已选', point_jd: lon, point_wd: lat})
        })
    };

    chageCity = () => {
        let self = this;
        ChooseCity(function (res) {
            let city = res.city;
            let code = res.code;
            self.setState({cityName: city, cityCode: code});
        })
    };

    changeLogo = () => {
        this.chooseImg(IMGTYPE.ShopLogo);
    }

    editStory = () => {
        let self = this;
        editRichContent({title: "店铺详情",
                         filetag: "shop",
                         value: this.state.story}, 
                         function(res) {
                            self.setState({story: res.value, storyState: res.value == '' ? '未编辑' : '已编辑'
                         });
        });
    }


    render() {
        let {width, height} = Dimensions.get('window');

        //门店图片
        let shopImgView;
        if (this.state.shopImgUri.length == 0) {
            shopImgView = (
                <TouchableOpacity onPress={() => this.chooseImg(IMGTYPE.ShopImage)}>
                    <View style={{flexDirection: 'column', alignItems: 'center'}}>
                        <View style={{
                            borderRadius: 30,
                            width: 60,
                            height: 60,
                            backgroundColor: themeconfig.maincolor,
                            marginBottom: 10,
                            justifyContent: 'center',
                            alignItems: 'center'
                        }}>
                            <Image source={require('../../image/img_camera.png')} style={{width: 35, height: 35}}/>
                        </View>
                        <Text>选择照片</Text>
                    </View></TouchableOpacity>);
        } else {
            shopImgView = (<TouchableOpacity onPress={() => this.chooseImg(IMGTYPE.ShopImage)}>
                <Image
                    style={styles.shopImgStyle}
                    source={{uri: this.state.shopImgUri}}/>
            </TouchableOpacity>);
        }

        //用户头像
        // let userHeadView;
        // if (this.state.userHeadUri.length == 0) {
        //     userHeadView = (
        //         <TouchableOpacity onPress={() => this.chooseImg(IMGTYPE.UserHeadImg)}>
        //             <View style={{
        //                 borderRadius: 20,
        //                 width: 40,
        //                 height: 40,
        //                 backgroundColor: themeconfig.maincolor,
        //                 justifyContent: 'center',
        //                 alignItems: 'center'
        //             }}>
        //                 <Image source={require('../../image/img_camera.png')} style={{width: 25, height: 25}}/>
        //             </View>
        //         </TouchableOpacity>);
        // } else {
        //     userHeadView = (<TouchableOpacity onPress={() => this.chooseImg(IMGTYPE.UserHeadImg)}>
        //         <Image style={styles.itemBar_Image_Round}
        //                source={{uri: this.state.userHeadUri}}/></TouchableOpacity>);
        // }

        let shoplogo = require('../../image/img_shop_complete_logo.png')
        if (this.state.shoplogo != '' && this.state.shoplogo != undefined) {
            shoplogo = {uri: this.state.shoplogo}
        }

        let brandsView = undefined
        if (this.state.brandLicence == '' || this.state.brandLicence == undefined) {
            brandsView = <View/>;
        } else {
            brandsView = <View style={{alignItems: 'center'}}>
                {
                    this.state.brandLicence.split(';').map((item) => {
                        return <Image style={{marginTop: 10, width: width - 40, height: (width - 40) / 2 * 3}} source={{uri: item}}/>
                    })
                }
            </View>;
        }

        return (
            <ScrollView style={{flex: 1, backgroundColor: '#ebebeb'}}>
                {/*步骤信息标题*/}
                {/* <View style={styles.stepViewStyle}>
                    <Text style={styles.stepTxtStyle}>第一步:完善昵称与头像</Text>
                </View>
                <View style={styles.itemBar}>
                    <Text style={styles.itemBar_Text}>昵称</Text>
                    <TextInput
                        style={styles.itemBar_Input}
                        value={this.state.nick}
                        onChangeText={(txt) => {
                            this.setState({nick: txt})
                        }}
                        underlineColorAndroid={'transparent'}/>
                </View>
                <View style={styles.line_gray}/>
                <View style={styles.itemBar}>
                    <Text style={styles.itemBar_Text}>联系电话</Text>
                    <TextInput
                        style={styles.itemBar_Input}
                        value={this.state.phone}
                        onChangeText={(txt) => {
                            this.setState({phone: txt})
                        }}
                        underlineColorAndroid={'transparent'}/>
                </View>
                <View style={styles.line_gray}/>

                <View style={styles.itemBar}>
                    <Text style={styles.itemBar_Text}>头像</Text>
                    <View style={{
                        flex: 1, flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-between'
                    }}>
                        <Text style={{flex: 1}}>点击上传头像</Text>
                        {userHeadView}
                    </View>
                </View> */}

                <View style={styles.stepViewStyle}>
                    <Text style={styles.stepTxtStyle}>第一步:店铺基本信息</Text>
                </View>
                <TouchableOpacity onPress={this.changeLogo}>
                    <View style={[styles.stepViewStyle, {padding: 20}]}>
                        <Image style={{width: 60, height: 60}} source={shoplogo}/>
                    </View>
                </TouchableOpacity>
                <View style={styles.itemBar}>
                    <Text style={styles.itemBar_Text}>店铺名称</Text>
                    <TextInput
                        style={styles.itemBar_Input}
                        value={this.state.shopName}
                        onChangeText={(txt) => {
                            this.setState({shopName: txt})
                        }}
                        underlineColorAndroid={'transparent'}/>
                </View>
                <View style={styles.line_gray}/>
                <View style={styles.itemBar}>
                    <Text style={styles.itemBar_Text}>联系电话</Text>
                    <TextInput
                        style={styles.itemBar_Input}
                        value={this.state.phone}
                        onChangeText={(txt) => {
                            this.setState({phone: txt})
                        }}
                        keyboardType='number-pad'
                        underlineColorAndroid={'transparent'}/>
                        
                </View>
                <View style={styles.line_gray}/>
                <TouchableOpacity onPress={this.chageCity}>
                    <View style={styles.itemBar}>
                        <Text style={styles.itemBar_Text}>所在地区</Text>
                        <View style={{flex: 1}}></View>
                        <Text style={styles.itemBar_Text}>{this.state.cityName}</Text>
                        <Image style={{width: 20, height: 20}} source={require('../../image/img_right_grey.png')}/>
                    </View>
                </TouchableOpacity>
                <View style={{backgroundColor: 'white'}}>
                    <View style={{marginLeft: 20, backgroundColor: '#eee', height: 1}}/>
                </View>
                <View style={styles.itemBar}>
                    <TextInput
                        underlineColorAndroid={'transparent'}
                        style={styles.itemBar_Input}
                        value={this.state.address}
                        onChangeText={(txt) => {
                            this.setState({address: txt})
                        }}
                        placeholder={'请输入详细店铺地址'}/>
                </View>
                <View style={styles.line_gray}/>
                <TouchableOpacity onPress={this.changePlace}>
                    <View style={styles.itemBar}>
                        <Text style={styles.itemBar_Text}>位置信息</Text>
                        <View style={{flex: 1}}></View>
                        <Text style={styles.itemBar_Text}>{this.state.pointstate}</Text>
                        <Image style={{width: 20, height: 20}} source={require('../../image/img_right_grey.png')}/>
                    </View>
                </TouchableOpacity>
                {/* <View style={styles.line_gray}/>
                <View style={styles.itemBar}>
                    <Text style={styles.itemBar_Text}>品牌</Text>
                    <View style={{flex: 1}}></View>
                    <Text style={styles.itemBar_Text}>{this.state.brand}</Text>
                    <Image style={{width: 20, height: 20}} source={require('../../image/img_right_grey.png')}/>
                </View>
                <View style={styles.line_gray}/> */}
                <View style={styles.stepViewStyle}>
                    <Text style={styles.stepTxtStyle}>第二步:店铺装修</Text>
                </View>
                {/*店铺门店*/}
                <View style={styles.chooseImgViewStyle}>
                    {shopImgView}
                </View>
                <View style={styles.line_gray}/>
                <TouchableOpacity onPress={this.editStory}>
                    <View style={styles.itemBar}>
                        <Text style={styles.itemBar_Text}>店铺详情</Text>
                        <View style={{flex: 1}}></View>
                        <Text style={styles.itemBar_Text}>{this.state.storyState}</Text>
                        <Image style={{width: 20, height: 20}} source={require('../../image/img_right_grey.png')}/>
                    </View>
                </TouchableOpacity>
                <View style={styles.stepViewStyle}>
                    <Text style={styles.stepTxtStyle}>第三步:品牌资质(可选)</Text>
                </View>
                {brandsView}
                <View style={{marginTop: 20, alignItems: 'center'}}>
                    <Text style={{fontSize: 18}}>上传品牌授权书</Text>
                    <TouchableOpacity onPress={() => {
                        this.chooseImg(IMGTYPE.ShopBrand);
                    }}>
                        <Image style={{marginTop: 10, width: width - 40, height: (width - 40) / 866 * 539}} 
                               source={require('../../image/img_brand.png')}
                        />
                    </TouchableOpacity>
                </View>
                {/*合同明细*/}
                <View style={{alignItems: 'center', margin: 10, flexDirection: 'row', justifyContent: 'center'}}>
                    <CheckBox
                        label=''
                        onChange={(checked) => this.changeIsRead(checked)}
                        checkedImage={require('../../image/img_checked.png')}
                        uncheckedImage={require('../../image/img_check_no.png')}
                    />
                    <View style={{width: 10}}/>
                    <View style={{paddingBottom: 5, flexDirection: 'row', alignItems: 'center'}}>
                        <Text style={{marginRight: 3}}>已阅读</Text>
                        <TouchableOpacity onPress={() => navi(false, 'http://www.hongheyu1688.com/compact.html', {})}>
                            <Text style={{fontWeight: 'bold', fontSize: 16}}>合同明细</Text>
                        </TouchableOpacity>
                        <Text style={{marginLeft: 3}}>并同意相关规定</Text>
                    </View>
                </View>
                <TouchableOpacity onPress={() => this.submitAction()}>
                    <View style={{
                        marginLeft: 20,
                        marginRight: 20,
                        marginTop: 10,
                        marginBottom: 20,
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'center',
                        borderRadius: 5,
                        backgroundColor: themeconfig.maincolor,
                        minHeight: 48
                    }}>
                        <Text style={{color: '#fff', fontSize: 15}}>提交</Text>
                    </View>
                </TouchableOpacity>

                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    cancelButtonIndex={CANCEL_INDEX}
                    onPress={this.handlePress}
                    options={options}/>
            </ScrollView>
        );
    }
}


const mapStateToProps = state => ({
        userToken: state.mainmodel.userToken,
        token: state.mainmodel.token,
    });

const mapDispatchToProps = dispatch => ({
        getShopInfoCallBack: (token, success) => {
            dispatch(getShopInfoCallBack(token, success))
        },
        saveShopInfo: (params, success) => {
            dispatch(saveShopInfo(params, success))
        },
        submitShopInfo: (params, success) => {
            dispatch(submitShopInfo(params, success))
        },
        authShops: (params, success) => {
            dispatch(authShops(params, success))
        },
        naviBack: (value) => {
            dispatch(naviBack(value))
        },
        getShopInfo: () => {
            dispatch(getShopInfo());
        }
    });


export default connect(
    mapStateToProps,
    mapDispatchToProps)
    (ShopComplete);


